import 'dart:io';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

class FileManager {

  /// 创建 `FileManager` 单一实例
  FileManager._internal();
  static FileManager? _singleton;
  static FileManager instance() {
    // 如果 `_singleton` 为空则 `_singleton == FileManager._internal()`
    _singleton ??= FileManager._internal();
    return _singleton!;
  }


  // 读 json 数据
  Future<String> readJson() async {

    try {
      final File file = await _localFile;
      String content = await file.readAsString();
      return json.decode(content);
    } catch (e) {
      if (kDebugMode) {
        print('FileManager Read ==> $e');
      }
    }
    return '';
  }

  // 写 json 数据'
  Future<File> writeJson(jsons) async {

    final File file = await _localFile;
    return file.writeAsString(json.encode(jsons), mode: FileMode.append);
  }


  // 读文件内容
  Future<String> readFile() async {

    final File file = await _localFile;
    String content = await file.readAsString();
    return content;
  }

  // 写文件内容
  Future<File> writeFile(String text) async {

    final File file = await _localFile;
    return file.writeAsString(text, mode: FileMode.append);
  }

  
  // 清空文件
  Future<File> cleanFile() async {
    
    final File file = await _localFile;
    return file.writeAsString('');
  }

  // 存放的文件
  Future<File> get _localFile async {

    final String path = await localPath;
    // final File file = File('$path/assets/local.txt');
    final File file = File('$path/local/files.txt');
    return file;
  }

  // 存放的文件目录
  Future<String> get localPath async {

    final Directory directory = await getApplicationDocumentsDirectory();
    final String path = directory.path;
    return path;
  }
}